package com.yin.waimai.service.impl;

import com.yin.waimai.config.RabbitMQConfig;
import com.yin.waimai.dto.OrderNotificationDTO;
import com.yin.waimai.service.NotificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.regex.Pattern;

/**
 * 通知服务实现类
 * 实现邮件发送和异步消息处理功能
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationServiceImpl implements NotificationService {

    private final JavaMailSender mailSender;
    private final RabbitTemplate rabbitTemplate;
    
    @Value("${spring.mail.username}")
    private String fromEmail;
    
    // 邮箱格式验证正则表达式
    private static final String EMAIL_PATTERN = 
        "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@" +
        "(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    
    private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN);

    /**
     * 发送订单状态变更邮件通知
     * @param orderNotification 订单通知信息
     */
    @Override
    public void sendOrderStatusEmailNotification(OrderNotificationDTO orderNotification) {
        if (!isValidNotification(orderNotification)) {
            return;
        }
        
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(orderNotification.getRecipientEmail());
            message.setSubject("物流订单状态更新 - 订单号: " + orderNotification.getOrderNumber());
            
            String content = buildOrderStatusEmailContent(orderNotification);
            message.setText(content);
            
            mailSender.send(message);
            log.info("订单状态变更邮件发送成功: 订单号={}, 收件人={}", 
                    orderNotification.getOrderNumber(), orderNotification.getRecipientEmail());
                    
        } catch (Exception e) {
            log.error("发送订单状态变更邮件失败: 订单号={}, 收件人={}, 错误信息={}", 
                    orderNotification.getOrderNumber(), orderNotification.getRecipientEmail(), e.getMessage(), e);
        }
    }

    /**
     * 发送订单创建确认邮件
     * @param orderNotification 订单通知信息
     */
    @Override
    public void sendOrderCreatedEmailNotification(OrderNotificationDTO orderNotification) {
        if (!isValidNotification(orderNotification)) {
            return;
        }
        
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(orderNotification.getRecipientEmail());
            message.setSubject("订单创建成功 - 订单号: " + orderNotification.getOrderNumber());
            
            String content = buildOrderCreatedEmailContent(orderNotification);
            message.setText(content);
            
            mailSender.send(message);
            log.info("订单创建确认邮件发送成功: 订单号={}, 收件人={}", 
                    orderNotification.getOrderNumber(), orderNotification.getRecipientEmail());
                    
        } catch (Exception e) {
            log.error("发送订单创建确认邮件失败: 订单号={}, 收件人={}, 错误信息={}", 
                    orderNotification.getOrderNumber(), orderNotification.getRecipientEmail(), e.getMessage(), e);
        }
    }

    /**
     * 发送配送完成邮件通知
     * @param orderNotification 订单通知信息
     */
    @Override
    public void sendDeliveryCompletedEmailNotification(OrderNotificationDTO orderNotification) {
        if (!isValidNotification(orderNotification)) {
            return;
        }
        
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(orderNotification.getRecipientEmail());
            message.setSubject("配送完成通知 - 订单号: " + orderNotification.getOrderNumber());
            
            String content = buildDeliveryCompletedEmailContent(orderNotification);
            message.setText(content);
            
            mailSender.send(message);
            log.info("配送完成邮件发送成功: 订单号={}, 收件人={}", 
                    orderNotification.getOrderNumber(), orderNotification.getRecipientEmail());
                    
        } catch (Exception e) {
            log.error("发送配送完成邮件失败: 订单号={}, 收件人={}, 错误信息={}", 
                    orderNotification.getOrderNumber(), orderNotification.getRecipientEmail(), e.getMessage(), e);
        }
    }

    /**
     * 发送异步邮件通知（通过RabbitMQ）
     * @param orderNotification 订单通知信息
     */
    @Override
    public void sendAsyncEmailNotification(OrderNotificationDTO orderNotification) {
        if (!isValidNotification(orderNotification)) {
            return;
        }
        
        try {
            rabbitTemplate.convertAndSend(
                RabbitMQConfig.NOTIFICATION_EXCHANGE,
                RabbitMQConfig.NOTIFICATION_ROUTING_KEY,
                orderNotification
            );
            log.info("异步邮件通知消息发送成功: 订单号={}, 收件人={}", 
                    orderNotification.getOrderNumber(), orderNotification.getRecipientEmail());
                    
        } catch (Exception e) {
            log.error("发送异步邮件通知消息失败: 订单号={}, 收件人={}, 错误信息={}", 
                    orderNotification.getOrderNumber(), orderNotification.getRecipientEmail(), e.getMessage(), e);
        }
    }

    /**
     * 验证邮箱地址格式
     * @param email 邮箱地址
     * @return 是否有效
     */
    @Override
    public boolean isValidEmail(String email) {
        return StringUtils.hasText(email) && pattern.matcher(email).matches();
    }

    /**
     * 验证通知信息是否有效
     * @param orderNotification 订单通知信息
     * @return 是否有效
     */
    private boolean isValidNotification(OrderNotificationDTO orderNotification) {
        if (orderNotification == null) {
            log.warn("订单通知信息为空");
            return false;
        }
        
        if (!StringUtils.hasText(orderNotification.getRecipientEmail())) {
            log.warn("收件人邮箱为空: 订单号={}", orderNotification.getOrderNumber());
            return false;
        }
        
        if (!isValidEmail(orderNotification.getRecipientEmail())) {
            log.warn("收件人邮箱格式无效: 订单号={}, 邮箱={}", 
                    orderNotification.getOrderNumber(), orderNotification.getRecipientEmail());
            return false;
        }
        
        return true;
    }

    /**
     * 构建订单状态变更邮件内容
     * @param orderNotification 订单通知信息
     * @return 邮件内容
     */
    private String buildOrderStatusEmailContent(OrderNotificationDTO orderNotification) {
        StringBuilder content = new StringBuilder();
        content.append("尊敬的客户，您好！\n\n");
        content.append("您的订单状态已更新：\n\n");
        content.append("订单号：").append(orderNotification.getOrderNumber()).append("\n");
        content.append("当前状态：").append(getStatusDisplayName(orderNotification.getOrderStatus())).append("\n");
        
        if (StringUtils.hasText(orderNotification.getLocation())) {
            content.append("当前位置：").append(orderNotification.getLocation()).append("\n");
        }
        
        if (StringUtils.hasText(orderNotification.getDescription())) {
            content.append("状态描述：").append(orderNotification.getDescription()).append("\n");
        }
        
        content.append("\n感谢您使用我们的物流服务！\n");
        content.append("\n此邮件为系统自动发送，请勿回复。");
        
        return content.toString();
    }

    /**
     * 构建订单创建确认邮件内容
     * @param orderNotification 订单通知信息
     * @return 邮件内容
     */
    private String buildOrderCreatedEmailContent(OrderNotificationDTO orderNotification) {
        StringBuilder content = new StringBuilder();
        content.append("尊敬的客户，您好！\n\n");
        content.append("您的订单已成功创建：\n\n");
        content.append("订单号：").append(orderNotification.getOrderNumber()).append("\n");
        content.append("寄件人：").append(orderNotification.getShipperName()).append("\n");
        content.append("收件人：").append(orderNotification.getRecipientName()).append("\n");
        
        if (orderNotification.getCalculatedFee() != null) {
            content.append("运费：￥").append(orderNotification.getCalculatedFee()).append("\n");
        }
        
        content.append("\n我们将尽快为您安排配送，请耐心等待。\n");
        content.append("\n感谢您使用我们的物流服务！\n");
        content.append("\n此邮件为系统自动发送，请勿回复。");
        
        return content.toString();
    }

    /**
     * 构建配送完成邮件内容
     * @param orderNotification 订单通知信息
     * @return 邮件内容
     */
    private String buildDeliveryCompletedEmailContent(OrderNotificationDTO orderNotification) {
        StringBuilder content = new StringBuilder();
        content.append("尊敬的客户，您好！\n\n");
        content.append("您的订单已成功配送完成：\n\n");
        content.append("订单号：").append(orderNotification.getOrderNumber()).append("\n");
        content.append("收件人：").append(orderNotification.getRecipientName()).append("\n");
        
        if (StringUtils.hasText(orderNotification.getLocation())) {
            content.append("签收地点：").append(orderNotification.getLocation()).append("\n");
        }
        
        content.append("\n感谢您使用我们的物流服务，期待下次为您服务！\n");
        content.append("\n此邮件为系统自动发送，请勿回复。");
        
        return content.toString();
    }

    /**
     * 获取状态显示名称
     * @param status 状态枚举值
     * @return 显示名称
     */
    private String getStatusDisplayName(String status) {
        if (status == null) return "未知状态";
        
        switch (status) {
            case "PENDING_COLLECTION": return "待揽件";
            case "COLLECTED": return "已揽件";
            case "TRANSPORTING": return "运输中";
            case "OUT_FOR_DELIVERY": return "派送中";
            case "SIGNED": return "已签收";
            case "COMPLETED": return "已完成";
            case "DELIVERY_FAILED": return "配送失败";
            default: return status;
        }
    }
}